<?php
/**
 * 在前台使用此helper。后台使用MForm->swfupload
 * @author arlon
 *
 */
class SwfuploadHelper extends FormHelper {
	
	var $helpers = array('Html','Form');
	public static $js_loaded = false;
	
	function html5($file_post_name = 'Filedata',$param = array()){
		$this->setEntity($file_post_name);
		$fieldname = $this->field(); //$file_post_name可能含“.”,经过field函数处理后，不含‘.’，得到name值
		$hidden = $this->Form->hidden($file_post_name,array('value'=>$param['value']));
		
		$locale = $this->_View->getVar('locale');
		
		//no_db支持从外部方法中传入，即在模板中指定值。其他都保存至uploadfiles表
		$param = array_merge(array(
				'modelClass'=> 'Article',
				'isadmin' => true,
				'label' => __d('i18nfield','Field_'.$param['modelClass'].'_'.$fieldname),
				
				'no_db' =>0, // 是否不保存到数据库uploadfiles
				'no_thumb'=>1,//图片不生成缩略图
				'save_folder' => '', // 保存地址
				
				'return_type'=> 'json',// html or json
				'with_list_div' => true,
				'withprogress'=>true // 是否显示上传进度
		),$param);
		//extract($param); // 变量混淆方法不支持extract，直接用数组来使用变量
		
		if(strpos($file_post_name,'.')===false){
			$fieldid = $param['modelClass'].'.'.$file_post_name;
		}
		
		$fieldid = Inflector::camelize (str_replace('.','_',$file_post_name));
		
		$listfile = '';
		if(isset($this->data['Uploadfile']) && is_array($this->data['Uploadfile']) && is_array($this->data['Uploadfile'][$file_post_name])){
			foreach($this->data['Uploadfile'][$file_post_name] as $uploadfile){
				//if($uploadfile['fieldname']==$file_post_name)
				{
					$listfile.='<div class="upload-fileitem pull-left" id="upload-file-'.$uploadfile['id'].'">';
					if(substr($uploadfile['fspath'],0,7) != 'http://'){
						$file_url = str_replace('//','/',UPLOAD_FILE_URL.($uploadfile['fspath']));
					}
					else{
						$file_url = $uploadfile['fspath'];
					}
		
					$file_size = getHumanFileSize($uploadfile['size']);
		
					if('image' == substr($uploadfile['type'],0,5)){
						
						$listfile.='<div class="btn" style="background-image:url('.$file_url.');" title="'.$uploadfile['name'].'">
					                  	<div class="filename">'.$uploadfile['name'].'</div>
					                  	<small class="filesize">'.$file_size.'</small>
					                </div>';
					}
					else{
						$listfile.='<a class="btn btn-success " title="'.$uploadfile['name'].'" href="'.$this->Html->url('/uploadfiles/download/'.$uploadfile['id']).'" target="_blank">
					                  	<i class="glyphicon glyphicon-cloud-download"></i>
					                  	<div class="filename">'.$uploadfile['name'].'</div>
					                  	<small class="filesize">'.$file_size.'</small>
					                  </a>';
					}
					$listfile.='<i class="glyphicon glyphicon-remove remove" data-id="'.$uploadfile['id'].'" title="'.lang('remove this file').'"></i>';
					$listfile.='<input type="hidden" name="data[Uploadfile]['.$uploadfile['id'].'][id]" value="'.$uploadfile['id'].'"></div>';
				}
			}
		}
		if( empty($listfile) && ( (isset($this->data[$param['modelClass']][$fieldname]) && !empty($this->data[$param['modelClass']][$file_post_name])) || !empty($param['value']) ) ) {
			// 上传文件的地址保存到本模块对应的字段中，而非保存在Uploadfile里
			if($param['value']){
				if(substr($param['value'],0,7) != 'http://'){
					$file_url = UPLOAD_FILE_URL.($param['value']);
				}
				else{
					$file_url = $param['value'];
				}
			}
			else{
				if(substr($this->data[$param['modelClass']][$file_post_name],0,7) != 'http://'){
					$file_url = UPLOAD_FILE_URL.($this->data[$param['modelClass']][$file_post_name]);
				}
				else{
					$file_url = $this->data[$param['modelClass']][$file_post_name];
				}
			}
			if(is_image($file_url)){
				$listfile .= '<a href="'.$file_url.'" title="'.__( 'Preview').'" target="_blank"><img src="'.$file_url.'" style="max-height:120px"/></a>';
			}
			else{
				$listfile .= '<a href="'.$file_url.'" target="_blank">'.__( 'Preview').'</a>';
			}
		}
		if($param['isadmin']){
			$upload_url = $this->Html->url('/admin/uploadfiles/upload');
		}
		else{
			$upload_url = Router::url('/uploadfiles/upload');
		}
		$upload_html = '<input id="'.$fieldid.'" type="file" name="'.$fieldname.'" onchange=""><script>
		$(function(){
			$("#'.$fieldid.'").change(function(e){
					var id = "'.$fieldname.'";
					var u = new Html5Uploadfile(id);
					u.upload(this,{
							file_post_name: \''.$fieldname.'\',	
							file_model_name:\''.$param['modelClass'].'\',
							upload_url: \''.$upload_url.'\',
							no_db:\''.$param['no_db'].'\',
							data_id:\''.$param['data_id'].'\',
							item_css:\''.$param['item_css'].'\',
							save_folder:\''.$param['save_folder'].'\',
							return_type:\''.$param['return_type'].'\'
					})
			})			
		});			
		</script>';
		//flash_url 不能使用Html->script,会自动增加.js的后缀。用图片url的函数即可。HtmlHelper中增加了函数onlyurl参数直接返回url
		return $hidden.'<div class="form-group swfupload-control" >'.
				($param['label']?'<label class="control-label">'.$param['label'].'</label>':'').
				'<div class="controls">
						'.$upload_html.($param['with_list_div']? '
						<div class="alert alert-info">'.__('submit_after_upload_success_tips').'</div>
						<div class="upload-filelist row" id="fileuploadinfo_'.$fieldname.'">
							'.$listfile.'
						</div>' :'').'
		
				</div>
		
		</div>';
	}

	function load($file_post_name = 'Filedata',$param = array()) {
		
		if(defined('IS_MOBILE')){
			return $this->html5($file_post_name,$param);
		}
		
		$this->setEntity($file_post_name);
		
		$size = 0;
		if( isset($param['size']) && intval($param['size']) ) {
		    $size = intval($param['size']);
		}
		else {
		    $size = Configure::read('Download.upload_limit');
		}
		if(empty($size)) {
		    $size = 2;
		}
		if(!is_array($param)){
			$param = array('modelClass'=>$param);
		}
// 		var_dump($this->Form);exit;
// 		print_r($this->model());
		
		if(strpos($file_post_name,'.')===false){
			$fieldid = Inflector::camelize (str_replace('.','_',$param['modelClass'].'.'.$file_post_name));
		}
		else{
		    $fieldid = Inflector::camelize (str_replace('.','_',$file_post_name));
		}
		
		
		
		$fieldname = $this->field(); //$file_post_name可能含“.”,经过field函数处理后，不含‘.’，得到name值
		
		
		$locale = $this->_View->getVar('locale');

		
		//no_db支持从外部方法中传入，即在模板中指定值。其他都保存至uploadfiles表
		$param = array_merge(array(
				'modelClass'=> 'Article',
				'isadmin' => true,
				'label' => __d('i18nfield','Field_'.$param['modelClass'].'_'.$fieldname),
				'after' => '',//描述
				'upload_limit'=> 0, // 最多允许上传的文件数，0为不限制
				'file_types'=> "*.*", // '*.jpg;*.gif;*.png,*.bmp',
				'file_types_description'=> 'All Files',
				'button_image_url'=> '/img/'.$locale.'/uploadbutton.png', // 上传按钮描述
				'button_width'=> 110, // 上传按钮宽度
				'button_height'=> 35, // 上传按钮高度
				'no_db' =>0, // 是否不保存到数据库uploadfiles
				'no_thumb'=>0,//图片不生成缩略图
				'save_folder' => '', // 保存地址	
				'fieldid' => '',
		        'js_loaded' => false,
				'required' => false,
				'upload_success_handler'=>'uploadSuccess', //回调函数
				'upload_success_addon' => '',
				'file_upload_progress' => 'fsUploadProgress_'.$fieldid,
				'return_type'=> 'json',// html or json
				'remote_type' => 'oss',
		        'input_type' => 'text',
				'with_list_div' => true,
				'withprogress'=>true // 是否显示上传进度
				),$param);
		//extract($param); // 变量混淆方法不支持extract，直接用数组来使用变量
		if( $param['no_db'] ) {
			$param['upload_limit'] = 1;
		}
		
		if( $param['upload_limit'] == 1 && $param['upload_success_handler']=='uploadSuccess'){
			
			$param['upload_success_handler'] = 'uploadSuccess_'.$fieldid;
			$hidden = $this->Form->input($file_post_name,array(
					'id'=>$fieldid,'class'=>'form-control','required'=>$param['required'],'type' => $param['input_type'],'label'=>false,'div'=>false,'placeholder' =>  __('Upload a file or input a file url.'),
					'value'=>$param['value']
			));
		}
		else{
			$hidden = $this->Form->hidden($file_post_name,array('id'=>$fieldid,'value'=>$param['value']));
		}
		
        $listfile = '';
        if(isset($this->data['Uploadfile']) && is_array($this->data['Uploadfile']) && is_array($this->data['Uploadfile'][$file_post_name])){
	        foreach($this->data['Uploadfile'][$file_post_name] as $uploadfile){
	        	//if($uploadfile['fieldname']==$file_post_name)
	        	{
	        		$listfile.='<div class="upload-fileitem pull-left" id="upload-file-'.$uploadfile['id'].'">';	        		
                    if(substr($uploadfile['fspath'],0,7) != 'http://'){
                        $file_url = str_replace('//','/',UPLOAD_FILE_URL.($uploadfile['fspath']));
                    }
                    else{
                        $file_url = $uploadfile['fspath'];
                    }

                    $file_size = getHumanFileSize($uploadfile['size']);
                    
	        		if('image' == substr($uploadfile['type'],0,5)){

						$listfile.='<div class="btn" title="'.$uploadfile['name'].'">
					                  	<img class="glyphicon-cloud-download" src="'.$file_url.'"/>
					                  	<div class="filename">'.$uploadfile['name'].'</div>
					                  	<small class="filesize">'.$file_size.'</small>
					                  </div>';
					}
					else{
						$listfile.='<a class="btn" title="'.$uploadfile['name'].'" href="'.$this->Html->url('/uploadfiles/download/'.$uploadfile['id']).'" target="_blank">
					                  	<i class="glyphicon glyphicon-cloud-download"></i>
					                  	<div class="filename">'.$uploadfile['name'].'</div>
					                  	<small class="filesize">'.$file_size.'</small>
					                  </a>';
					}
					$listfile.='<i class="glyphicon glyphicon-remove remove" data-id="'.$uploadfile['id'].'" title="'.lang('remove this file').'"></i>';
	        		$listfile.='<input type="hidden" name="data[Uploadfile]['.$uploadfile['id'].'][id]" value="'.$uploadfile['id'].'"></div>';
	        	}
	        }
        }
        if( empty($listfile) && ( (isset($this->data[$param['modelClass']][$fieldname]) && !empty($this->data[$param['modelClass']][$file_post_name])) || !empty($param['value']) ) ) {
        	// 上传文件的地址保存到本模块对应的字段中，而非保存在Uploadfile里
        	if($param['value']){
        		if(substr($param['value'],0,7) != 'http://'){
        			$file_url = UPLOAD_FILE_URL.($param['value']);
        		}
        		else{
        			$file_url = $param['value'];
        		}
        	}
        	else{
        		if(substr($this->data[$param['modelClass']][$file_post_name],0,7) != 'http://'){
        			$file_url = UPLOAD_FILE_URL.($this->data[$param['modelClass']][$file_post_name]);
        		}
        		else{
        			$file_url = $this->data[$param['modelClass']][$file_post_name];
        		}
        	}
        	if(is_image($file_url)){
        		$listfile .= '<div class="col-sm-12"><a href="'.$file_url.'" title="'.__( 'Preview').'" target="_blank"><img src="'.$file_url.'" style="max-height:120px"/></a></div>';
        	}
        	else{
        		$listfile .= '<div class="col-sm-12"><a href="'.$file_url.'" target="_blank">'.__( 'Preview').'</a></div>';
        	}
        }
        $qn_params = '';
        if($param['qiniu']) {
            $upload_url = 'http://upload.qiniu.com/';
            App::uses('CrawlUtility', 'Utility');
            $token = CrawlUtility::qiniuToken();
            $qn_params = '"token":"'.$token.'","x:model":"'.$param['modelClass'].'","x:field":"'.$fieldname.'","x:uid":"'.$this->Session->read('Auth.User.id').'",';
        }
        else{
            if($param['isadmin']){
                $upload_url = $this->Html->url('/admin/uploadfiles/upload');
            }
            else{
                $upload_url = Router::url('/uploadfiles/upload');
            }
        }

        $script = '<script>
'.(($param['upload_limit']==1)?
'function '.$param['upload_success_handler'].'(file, serverData) {
				try {
					var progress = progress_list[file.id] ;
					progress.setComplete();
					if (serverData === " ") {
						this.customSettings.upload_successful = false;
					} else {
						var data=eval("(" + serverData + ")");
						if(data.ret==0 || data.state=="SUCCESS"){
							this.customSettings.upload_successful = true;
							$("#'.$fieldid.'").val(data.fspath);
                            '.($param['upload_success_addon'] ? 'if(typeof '.$param['upload_success_addon'].' == "function") {
                                '.$param['upload_success_addon'].'(data);
                            }':'')
                            .'$("#fileuploadinfo_'.$fieldid.'").html(data.message);
						}
                        else{
                            if(data.error) {
            					alert(data.error);
            				}
                        }
					}
				} catch (e) {
					alert(serverData);
				}
			}':'').
'var swfu_'.$fieldid.';
$(function () {
	swfu_'.$fieldid.' = new SWFUpload({
		upload_url: "'.$upload_url.'",	
		file_post_name: "'.$fieldname.'",
		file_size_limit : "'.$size.' MB",
		file_types : "'.$param['file_types'].'",
		file_types_description : "'.$param['file_types_description'].'",
		file_upload_limit : 0,
		file_queue_limit : '.$param['upload_limit'].',
		post_params : {
			"PHP_SESSION_ID" : "'.session_id().'",
			"file_post_name" : "'.$fieldname.'",
			"file_model_name":"'.$param['modelClass'].'",
			"no_db":"'.$param['no_db'].'",
			"data_id":"'.$param['data_id'].'",
			'.$qn_params.'
			"item_css":"'.$param['item_css'].'",
			"save_folder":"'.$param['save_folder'].'",
			"return_type":"'.$param['return_type'].'",
			"remote_type":"'.$param['remote_type'].'"
		},
		
		button_image_url : "'.$this->Html->image($param['button_image_url'],array('onlyurl'=>true)).'",
// 		button_text ： "'.__('Upload file').'",
// 		button_text_style : "color: #000000; font-size: 16pt;",
		button_placeholder_id : "spanButtonPlaceholder_'.$fieldid.'",
		button_width: '.$param['button_width'].',
		button_height: '.$param['button_height'].',
		
			
		flash_url : "'.$this->Html->image('/js/swfupload/swfupload.swf',array('onlyurl'=>true)).'",
		flash9_url : "'.$this->Html->image('/js/swfupload/swfupload_fp9.swf',array('onlyurl'=>true)).'",
		
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		
		swfupload_preload_handler : preLoad,
		swfupload_load_failed_handler : loadFailed,
		swfupload_loaded_handler : loadSuccess,
		
		upload_start_handler : uploadStart,'.($param['withprogress']?
		'upload_progress_handler : uploadProgress,':'').
		'upload_error_handler : uploadError,
		upload_success_handler : '.$param['upload_success_handler'].',
		upload_complete_handler : uploadComplete,
		custom_settings : {
			progress_target : "'.$param['file_upload_progress'].'",
			upload_successful : false,
			auto_start : true
		},
		debug: '.($_GET['debug']?'true':'false').'
	});
	swfu_array[swfu_array.length] = swfu_'.$fieldid.';
});
</script>';
        //flash_url 不能使用Html->script,会自动增加.js的后缀。用图片url的函数即可。HtmlHelper中增加了函数onlyurl参数直接返回url
        // $this->_View->append('bottomscript',$script);
        
        $js_files = '';
        if(!self::$js_loaded && !$param['js_loaded']){
        	$js_files = $this->Html->script(array(
				'swfupload/swfupload.js',
				'swfupload/swfupload.queue.js',
				'swfupload/swfupload.cookies.js',
				'swfupload/fileprogress.js',
				'swfupload/handlers.js',
			));
        	self::$js_loaded = true;
        }
        
        
        if($param['label']){        
			return $js_files.'<div class="form-group swfupload-control" style="margin-top: 2px;">'.
        		'<label class="col-sm-2 control-label">'.$param['label'].'</label>'.
				'<div class="col-sm-10 controls">
        				'.$hidden.'
        				<table class="table table-noborder upload-operate" style="margin:0 0;">
        				<tr><td width="120px" style="padding:2px 0 !important;"><span id="spanButtonPlaceholder_'.$fieldid.'"></span></td><td><div id="'.$param['file_upload_progress'].'"></div></td>
						</tr></table>
					'.($param['with_list_div']? '
						<div class="upload-filelist row" id="fileuploadinfo_'.$fieldid.'">
							'.$listfile.'
						</div>' :'').'
				</div>
			</div>'.$script; 
        }
        else{
        	return $js_files.'<div class="swfupload-control" style="margin-top: 2px;" >'.$hidden.
        			'<table class="table table-noborder upload-operate" style="margin:0 0;">
        				<tr><td width="120px" style="padding:2px 0 !important;"><span id="spanButtonPlaceholder_'.$fieldid.'"></span></td><td><div id="'.$param['file_upload_progress'].'"></div></td>
						</tr></table>
					'.($param['with_list_div']? '
						<div class="upload-filelist row" id="fileuploadinfo_'.$fieldid.'">
							'.$listfile.'
						</div>' :'').'
			</div>'.$script;
        }
    }


}
?>